<template>
  <div class="batch-add-agents">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm" labelPosition="top">
      <el-form-item label="起始工号:" prop="exten">
        <el-input v-model.trim="form.exten" :maxlength="5" :minlength="4" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码前缀设置:" prop="password">
        <el-input v-model.trim="form.password" type="password" autocomplete='new-password' readonly onfocus="this.removeAttribute('readonly')"></el-input>
        <div style="font-size: 12px;line-height: 15px;margin-bottom: 5px;">推荐密码前缀：{{randomPwd}}</div>
      </el-form-item>
      <el-form-item label="需要增加座席:" prop="count">
        <el-input v-model.trim="form.count" :maxlength="2" :minlength="1">
          <template slot="append">个</template>
        </el-input>
      </el-form-item>
      <el-form-item label="起始外显号:" prop="callerIDNum" v-if="flag !=='ecommerce'">
        <el-input v-model.trim="form.callerIDNum"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="batchRole">
        <el-select v-model="form.batchRole" placeholder="请选择角色">
        <el-option
          v-for="item in roles"
          :key="item._id"
          :label="item.display_name"
          :value="item._id">

        </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="版本" prop="uversion">
        <el-select v-model="form.uversion" placeholder="请选择版本">
          <el-option
            v-for="item in licenceType"
            :key="item.code_value"
            :label="item.code_name"
            :value="item.code_value">

          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import {checkform} from '@/utils/validate'
  export default {
    name: 'batchAddAgents',
    data () {
      let validateNum = (rule, value, callback) => {
        let message = checkform(value, 'Number3')
        if (message) {
          callback(new Error(this.$t(message)))
        } else {
          if (value < 1000) {
            callback(new Error('起始工号最少4位'))
          } else {
            callback()
          }
        }
      }
      let validateNum1 = (rule, value, callback) => {
        let message = checkform(value, 'Number3')
        if (message) {
          callback(new Error('起始外显号码必须为数字'))
        } else {
          callback()
        }
      }
      let validateCount = (rule, value, callback) => {
        let message = checkform(value, 'Number3')
        if (message) {
          callback(new Error(this.$t(message)))
        } else {
          if (value > 999) {
            callback(new Error('增加数量最大为999个'))
          } else {
            callback()
          }
        }
      }
      return {
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        roles: [], // 角色数组
        randomPwd: '', // 推荐密码
        rules: {
          batchRole: { required: true, message: '请填写角色', trigger: 'change' },
          uversion: { required: true, message: '请填写版本', trigger: 'change' },
          callerIDNum: [{validator: validateNum1, trigger: 'blur'}],
          count: [{ required: true, message: '请填需要增加座席', trigger: 'blur' },
            {validator: validateCount, trigger: 'blur'}
          ],
          exten: [{ required: true, message: '请填起始工号', trigger: 'blur' },
            {validator: validateNum, trigger: 'blur'}
          ],
          password: { required: true, message: '请填写密码前缀设置', trigger: 'blur' }
        },
        form: {
          exten: '', // 起始工号
          password: '', // 密码前缀设置
          count: '', // 需要增加座席
          callerIDNum: '', // 起始外显号码
          batchRole: '', // 角色
          uversion: '' // 版本
        },
        currPbxstatus: {
          title: '',
          type: ''
        } // 当前pbx的状态
      }
    },
    props: {
      licenceType: Array
    },
    components: {
    },
    watch: {
    },
    computed: {
      pbx () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    methods: {
      resetFormData () {
        this.form = {
          exten: '', // 起始工号
          password: '', // 密码前缀设置
          count: '', // 需要增加座席
          callerIDNum: '', // 起始外显号码
          batchRole: '', // 角色
          uversion: '' // 版本
        }
        this.initLicenceType()
        this.initRole()
        this.updatePwd()
        this.$nextTick(function () {
          this.$refs['form'].clearValidate()
        })
      },
      initLicenceType () {
        if (this.licenceType.length !== 0) {
          this.form.uversion = this.licenceType[0].code_value
        }
        for (let i = 0; i < this.licenceType.length; i++) {
          if (this.licenceType[i].code_value === 'enterprise') {
            this.form.uversion = this.licenceType[i].code_value
            break
          }
        }
      },
      initRole () {
        this.$store.dispatch('getCache', {type: 'roles'}).then((res) => {
          console.log(res)
          this.roles = res
          if (this.roles.length !== 0) {
            this.form.batchRole = this.roles[0]._id
          }
          for (let i = 0; i < this.roles.length; i++) {
            if (this.roles[i].display_name === '座席') {
              this.form.batchRole = this.roles[i]._id
              break
            }
          }
        })
      },
      randomWord (min, max) {
        let str = ''
        let range = min
        let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
        // 随机产生
        range = Math.round(Math.random() * (max - min)) + min
        for (let i = 0; i < range; i++) {
          let pos = Math.round(Math.random() * (arr.length - 1))
          str += arr[pos]
        }
        return str
      },
      updatePwd () {
        let _pattern = '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$'
        let _pwd = this.randomWord(8, 11)
        while (!_pwd.match(_pattern)) {
          _pwd = this.randomWord(8, 11)
        }
        let teStr = '#_!'
        let _numRan = Math.floor(Math.random() * 4)
        let _arrayStr = _pwd.split('')
        _arrayStr.splice(_numRan, 0, teStr.charAt(_numRan))
        this.randomPwd = _arrayStr.join('')
      },
      saveDispatch () {
        let data = {
          exten: this.form.exten,
          password: this.form.password,
          count: this.form.count,
          callerIDNum: this.form.callerIDNum,
          batchRole: this.form.batchRole,
          uversion: this.form.uversion,
          Account: this.$store.state.session.account.account,
          PBX: this.pbx
        }
        this.$store.dispatch('batchAddAgent', data).then((res) => {
          if (res.success) {
            this.$message.success('批量添加座席成功，请手动刷新！')
            this.$emit('batchAddAgentsSuccess')
          } else {
            if (res.reason) {
              this.$message.error('新增的工号区间与现有座席重复，请修改!')
            }
          }
        })
      },
      saveBatchAddAgents () {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.exten.length === 4 && (this.form.exten.substr(0, 1) === '0' || this.form.exten.substr(0, 1) === '9')) {
              this.$message.error('座席工号为4位数不能以数字0、9开头')
              return
            } else if (this.form.exten.length === 5 && (this.form.exten.substr(0, 1) === '0' || this.form.exten.substr(0, 1) === '9' || this.form.exten.substr(0, 1) === '1')) {
              this.$message.error('座席工号为5位数不能以数字0、1、9开头')
              return
            }
            // 密码校验
            let passwordNew = this.form.password
            if (passwordNew !== null && passwordNew !== '') {
              let regexPass = false
              let lengthRegex = new RegExp('^.{8,}$') // >= 8位
              let characterRegex = new RegExp('[a-z]') // 小寫
              let characterRegex2 = new RegExp('[A-Z]') // 大寫
              let numberRegex = new RegExp('[0-9]')// 數字
              let chinese = new RegExp('[\\u4E00-\\u9FFF]+', 'g') // 是否有中文
              let num = 0
              let temporary = this.form.password
              temporary = temporary.replace(/[^0-9a-zA-Z]/g, '')
              if (characterRegex.test(passwordNew)) {
                num += 1
              }
              if (characterRegex2.test(passwordNew)) {
                num += 1
              }
              if (numberRegex.test(passwordNew)) {
                num += 1
              }
              if ((passwordNew.length - temporary.length) > 0) {
                num += 1
              }
              if (num >= 3) {
                regexPass = true
              } else {
                regexPass = false
              }
              if (!lengthRegex.test(passwordNew)) {
                regexPass = false
              }
              if (chinese.test(passwordNew)) {
                regexPass = false
              }
              let limitArr = ['%', '&', '"', '\'', '<', '>', '+', '=']
              for (let i = 0; i < limitArr.length; i++) {
                if (passwordNew.indexOf(limitArr[i]) > -1) {
                  regexPass = false
                  break
                }
              }
              if (!regexPass) {
                this.$message.error(this.$t('config.agent.newPasswordRule'))
                return
              }
            }
            if (this.currPbxstatus.type === 'inverse') {
              this.$confirm('前pbx实例已饱和，建议不要再往该pbx上继续添加座席，具体详情请联系运维leader进行咨询', this.$t('public.tip'), {
                confirmButtonText: '继续添加',
                cancelButtonText: this.$t('public.cancel'),
                cancelButtonClass: 'primary_btn',
                confirmButtonClass: 'primary_btn',
                type: 'warning'
              }).then(() => {
                this.saveDispatch()
              })
            } else {
              this.saveDispatch()
            }
          }
        })
      }
    },
    mounted () {
      this.$store.dispatch('checkPbxLoadInfo', {'pbxId': this.pbx}).then((state) => {
        this.currPbxstatus = state
      })
    },
    beforeMount () {
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .margin-t-15
    margin-top 15px
  .agent-call-manage
    margin 20px
    overflow-y hidden
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    overflow-y: auto;
    font-size: 12px;
    .margin-l-10
      margin-left 10px
    .pag-wapper
      position: absolute;
      right: 15px;
      top: 14px;
    .main-color
      color $c-main
      cursor pointer
    .primary_btn
      padding 0px 10px
      min-width 60px
    .pink
      color $c-pink
      cursor pointer
</style>

